package com.kaifamiao.thread.d0927;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class Demo02 {

    public static void main(String[] args) {
        BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(2);
        Make m = new Make(blockingQueue);
        Runnable make = new Runnable() {
            @Override
            public void run() {
                while (true){
                    m.make();
                }
            }
        };
        Thread m1 = new Thread(make);

        Runnable eat = new Runnable() {
            @Override
            public void run() {
                while (true){
                    m.eat();
                }
            }
        };

        Thread e1 = new Thread(eat, "小明");
        Thread e2 = new Thread(eat, "小红");
        Thread e3 = new Thread(eat, "小蓝");

        m1.start();
        e1.start();
        e2.start();
        e3.start();
    }

}

class Make {
    private BlockingQueue<String> bq;

    public Make(BlockingQueue<String> blockingQueue){
        this.bq = blockingQueue;
    }

    public void make(){
        try {
            Thread.sleep(300);
            bq.put("鲜肉包"); // 判断是否有鲜肉包, 如果有就等待，如果没有才生产
            System.out.println("厨师放入一个鲜肉包");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void eat(){
        try {
            Thread.sleep(100);
            String take = bq.take(); // 如果没有就等待
            System.out.println(Thread.currentThread().getName() + " 将" + take + "拿出来吃了");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
